package logic

import (
	"context"
	"errors"
	"furni-manager/model/mysql"

	"furni-manager/furnirpc/furnirpc"
	"furni-manager/furnirpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FurniAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFurniAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FurniAddLogic {
	return &FurniAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FurniAddLogic) FurniAdd(in *furnirpc.FurniAddRequest) (*furnirpc.FurniAddResponse, error) {
	// todo: add your logic here and delete this line

	var furnis mysql.Furni
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&furnis)
	if furnis.ID != 0 {
		return nil, errors.New("家具已存在，请更换")
	}

	furni := mysql.Furni{
		Name:  in.Name,
		Price: float64(in.Price),
		Stock: int(in.Stock),
	}
	err := mysql.DB.Debug().Create(&furni).Error
	if err != nil {
		return nil, err
	}

	return &furnirpc.FurniAddResponse{
		FurniId: int64(furni.ID),
	}, nil
}
